﻿using Domain.Entity;
using DtoFw;
using DtoFw.Query;
using Repository;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Util;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SqlSugar;
using DtoFw.Enum;

namespace Service
{
    public class WarnService
    {

        private readonly CaseRepository _repository;
        private readonly WarnCheckoutRepository _warnCheckoutRepository;
        public WarnService(CaseRepository repository, WarnCheckoutRepository warnCheckoutRepository)
        {
            this._repository = repository;
            this._warnCheckoutRepository = warnCheckoutRepository;
        }

        /// <summary>
        /// 查询案件
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<Pager<WarnCheckoutDto>> QueryWarnCheckOut(WarnCheckoutDto dto)
        {

            int total = 0;
            Pager<WarnCheckoutDto> pager = new Pager<WarnCheckoutDto>();
            var linq = _repository.GetDb()
                 .Queryable<WarnCheckoutEntity>()
                  .Where(x => !x.IsDeleted)
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.CaseNo), x => x.CaseNo.Contains(dto.CaseNo))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.EvidenceName), x => x.EvidenceName.Contains(dto.EvidenceName))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.EvidenceNo), x => x.EvidenceNo.Contains(dto.EvidenceNo))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.InvNo), x => x.InvNo.Contains(dto.InvNo))
                       .WhereIF(dto.IsResolved.HasValue, x => x.IsResolved == dto.IsResolved)
                    .ToPageList(dto.Page, dto.PageSize, ref total);

            pager.Data = AutoMapperExtension.MapTo<WarnCheckoutEntity, WarnCheckoutDto>(linq);
            pager.TotalCount = total;

            return BaseGenericResult<Pager<WarnCheckoutDto>>.Succeed(pager);
        }

        /// <summary>
        /// 未绑定数据查询
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<Pager<WarnBindDto>> QueryWarnBind(WarnBindDto dto)
        {
            int total = 0;
            Pager<WarnBindDto> pager = new Pager<WarnBindDto>();
            var linq = _repository.GetDb()
                 .Queryable<WarnBindEntity>()
                  .Where(x => !x.IsDeleted)
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.CaseNo), x => x.CaseNo.Contains(dto.CaseNo))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.EvidenceName), x => x.EvidenceName.Contains(dto.EvidenceName))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.EvidenceNo), x => x.EvidenceNo.Contains(dto.EvidenceNo))
                    .WhereIF(!string.IsNullOrWhiteSpace(dto.InvNo), x => x.InvNo.Contains(dto.InvNo))
                    .WhereIF(dto.IsResolved.HasValue, x => x.IsResolved == dto.IsResolved)
                    .ToPageList(dto.Page, dto.PageSize, ref total);

            pager.Data = AutoMapperExtension.MapTo<WarnBindEntity, WarnBindDto>(linq);
            pager.TotalCount = total;

            return BaseGenericResult<Pager<WarnBindDto>>.Succeed(pager);
        }

        public BaseGenericResult<bool> HandleWarnBind(int hour)
        {
            try
            {
                //2小时之前的数据
                int hours = hour;

                //查询上一次的起止日期
                DateTime dt = DateTime.Now.AddDays(10000);

                var linq = _repository.GetDb().Queryable<WarnBindEntity>();
                if (linq.Any())
                {
                    dt = linq.Max(v => v.CreateTime);
                }

                List<CasePhysicalEvidenceEntity> entityList = _repository.GetDb().Queryable<CasePhysicalEvidenceEntity>()
                       .Where(v => v.CreateTime >= dt && v.CreateTime <= DateTime.Now.AddHours(-hours) && string.IsNullOrWhiteSpace(v.RFID)).ToList();

                foreach (var entity in entityList)
                {
                    var caselinq = _repository.GetDb().Queryable<CaseEntity>().Where(v => v.Id == entity.CaseId);
                    if (caselinq.Any())
                    {
                        var caseEntity = caselinq.Single();
                        _repository.GetDb().Insertable(new WarnCheckoutEntity()
                        {
                            CaseId = caseEntity.Id,
                            CaseName = caseEntity.CaseName,
                            CaseNo = caseEntity.CaseNo,
                            InvNo = caseEntity.InspectionNo,
                            EvidenceId = entity.Id,
                            EvidenceName = entity.Name,
                            EvidenceNo = entity.No,
                            IsResolved = 0,
                            CreateTime = DateTime.Now,
                            IsDeleted = false
                        }).ExecuteCommandAsync();
                    }
                }

                return BaseGenericResult<bool>.Succeed(true);
            }
            catch (Exception ex)
            {
                return BaseGenericResult<bool>.Failure(true, ex.ToString());
            }
        }
        /// <summary>
        /// 异常出库
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<WarnCheckoutRespDto> GetWarnCheckout()
        {
            WarnCheckoutRespDto warnCheckoutRespDto = new WarnCheckoutRespDto();
            warnCheckoutRespDto.list = _warnCheckoutRepository.GetDb().Queryable<NotificationEntity, CasePhysicalEvidenceEntity, CaseEntity>((t1, t2, t3) => new JoinQueryInfos(
                    JoinType.Left, t1.CheckId == t2.Id, JoinType.Left, t2.CaseId == t3.Id))
                    .Where(t1 => t1.Mold == (int)EalyWarnTypeEnum.eUnusualLevelWarning  && !t1.IsDeleted)
                      .OrderBy((t1, t2, t3) => t1.CreateTime, OrderByType.Desc)
                    .Select((t1, t2, t3) => new WarnCheckoutResp()
                    {

                        evidenceNo = t2.No,
                        evidenceName = t2.Name,
                        dt = t1.CreateTime,

                    })?.Take(20)?.ToList();


            foreach (var item in warnCheckoutRespDto.list)
            {
                item.date = item.dt.ToString("yyyy-MM-dd HH:mm:ss");
            }

            return BaseGenericResult<WarnCheckoutRespDto>.Succeed(warnCheckoutRespDto);
        }

        /// <summary>
        /// 首页硬件状态
        /// </summary>
        /// <returns></returns>
        public BaseGenericResult<EnvironmentDto> GetEnvironment()
        {
            EnvironmentDto dto = new EnvironmentDto();
            var entity = _repository.GetDb().Queryable<NotificationEntity>().Where(x => !x.IsDeleted && x.IsHandle == 1).ToList();
            dto.WenDu = entity.Where(x => x.Mold == 5)?.Count() > 0 ? false : true;
            dto.ShiDu = entity.Where(x => x.Mold == 6)?.Count() > 0 ? false : true;
            dto.YanGan = entity.Where(x => x.Mold == 7)?.Count() > 0 ? false : true;
            dto.ShuiQinChuanGan = entity.Where(x => x.Mold == 8)?.Count() > 0 ? false : true;
            dto.KongQiZhiLiang = entity.Where(x => x.Mold == 9)?.Count() > 0 ? false : true;
            return BaseGenericResult<EnvironmentDto>.Succeed(dto);
        }
    }
}
